<?php
/**
 * @link https://www.kancloud.cn/cleverstone/ymb2
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

namespace common\models;

use builder\helper\Str;
use builder\helper\Util;

/**
 * 管理员
 */
class AdminService
{
    /**
     * 获取账号列
     * @return array
     */
    public static function getColumnsWithUsername()
    {
        return Admin::query('username')->indexBy('id')->column();
    }

    /**
     * 表单下拉控件选项
     * @param string $nameField
     * @param string $valueField
     * @return array
     */
    public static function formSelectOptions(string $nameField = 'name', string $valueField = 'value'): array
    {
        return Admin::query([$nameField => 'username', $valueField => 'id'])->where('[[status]]=1')->all();
    }

    /**
     * 生成管理员账户接口访问令牌
     * @return string
     */
    public static function generateAccessToken()
    {
        $guid = Util::createGUID();
        $result = Admin::findOne(['access_token' => $guid]);
        if ($result) {
            return self::generateAccessToken();
        }
        return $guid;
    }

    /**
     * 生成唯一登录校验字符串
     * @return string
     */
    public static function generateSSOKEY()
    {
        return 'sso' . Str::random();
    }

    /**
     * 生成管理员邀请码
     * @return string
     */
    public static function generateInviteCode()
    {
        $codeChar = 'ic' . Str::random();
        $result = Admin::findOne(['invite_code' => $codeChar]);
        if ($result) {
            return self::generateInviteCode();
        }

        return $codeChar;
    }
}